package com.lin.websocket.server;

import lombok.extern.slf4j.Slf4j;
import org.java_websocket.WebSocket;
import org.java_websocket.handshake.ClientHandshake;
import org.java_websocket.server.WebSocketServer;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.InetSocketAddress;

/**
 * @作者: 林江
 * @创建时间: 2023/12/16
 * @功能: websocket服务端
 */
@Slf4j
public class MyWebSocketServer extends WebSocketServer {

    public MyWebSocketServer(InetSocketAddress address) {
        super(address);
    }

    public MyWebSocketServer(int port) {
        super(new InetSocketAddress(port));
    }

    /**
     * 客户端和服务端握手，开启连接
     */
    @Override
    public void onOpen(WebSocket conn, ClientHandshake handshake) {
        conn.send("Welcome to the server!"); // This method sends a message to the new client
        broadcast("new connection: " + handshake
                .getResourceDescriptor()); // This method sends a message to all clients connected
        System.out.println(
                conn.getRemoteSocketAddress().getAddress().getHostAddress() + " entered the room!");
    }

    /**
     * websocket关闭
     */
    @Override
    public void onClose(WebSocket conn, int code, String reason, boolean remote) {
        System.out.println("websocket关闭。。。。。。。。。");
        broadcast(conn + " has left the room!");
        System.out.println(conn + " has left the room!");

    }

    @Override
    public void onMessage(WebSocket conn, String message) {
        System.out.println("websocket服务端群发消息。。。。。。。。。");
        // 向订阅的客户端群发送消息。。。。。
        broadcast(message);
        System.out.println(conn + ": " + message);
    }

    /**
     * 负端异常的处理
     */
    @Override
    public void onError(WebSocket conn, Exception ex) {
        ex.printStackTrace();
        if (conn != null) {
            // some errors like port binding failed may not be assignable to a specific
            // websocket
        }

    }

    /**
     * websocket启动成功之后执行
     */
    @Override
    public void onStart() {
        System.out.println("Server started!");
        setConnectionLostTimeout(0);
        setConnectionLostTimeout(100);

    }

    public static void main(String[] args) throws IOException, InterruptedException {
        int port = 8887;
        // 构造连接地址
        WebSocketServer server = new MyWebSocketServer(port);
        server.start(); // 开启线程

        BufferedReader sysin = new BufferedReader(new InputStreamReader(System.in));
        while (true) {
            String in = sysin.readLine();
            server.broadcast(in);
            if (in.equals("exit")) {
                server.stop(1000);
                break;
            }
        }
        server.run();
    }
}
